﻿using AntUnion.FrameWork.Model.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AntUnion.FrameWork.Web.Areas.Console.Controllers
{
    public class SystemLogController : BaseController
    {
        private readonly IWebHostEnvironment _hostingEnv;
        private readonly _antunionContext _context;
        public SystemLogController(_antunionContext context, IWebHostEnvironment hostingEnv) : base(context, hostingEnv)
        {
            _context = context;
            _hostingEnv = hostingEnv;
        }

        #region 列表
        public IActionResult Index()
        {
            ViewBag.UserList = GetUserList();
            return View();
        }

        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<JsonResult> GetListJson(int page, int limit, int UserId = 0, string keyword = "")
        {
            ListResult res = new ListResult();
            try
            {
                var data = from n in _context.TbLogs.AsNoTracking()
                           join t in _context.TbUsers.AsNoTracking()
                           on n.Operator equals t.Id
                           select new
                           {
                               n.Operator,
                               n.Cont,
                               t.UserName,
                               n.Addtime
                           };
                if (UserId != 0)
                    data = data.Where(k => k.Operator == UserId);
                if (!string.IsNullOrEmpty(keyword))
                    data = data.Where(k => k.Cont.Contains(keyword));
                res.Data = await data.OrderByDescending(k => k.Addtime).Skip((page - 1) * limit).Take(limit).ToArrayAsync();

                res.Code = 0;
                res.Count = data.Count();
                return new JsonResult(res);
            }
            catch (Exception ex)
            {
                res.Code = 1;
                res.Msg = ex.Message;
                return new JsonResult(res);
            }
        }

        #endregion

        #region 获取下拉列表
        public SelectList GetUserList()
        {
            SelectList sl = null;
            var data = _context.TbUsers.Where(k => k.Id != 1).ToList();
            if (data.Count > 0)
            {
                IEnumerable<TbUser> ie = data.AsEnumerable();
                sl = new SelectList(ie, "Id", "UserName");
            }
            return sl;
        }
        #endregion
    }
}
